package com.heliang.common;

import java.io.BufferedInputStream;
import java.io.ByteArrayOutputStream;
import java.io.DataOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.HttpURLConnection;
import java.net.URL;

import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.Bitmap.CompressFormat;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;

import com.heliang.util.Constants;
import com.heliang.util.sinaweibo.HttpWeibo;
import com.heliang.util.sinaweibo.WeiboException;

/**
 * 
 * @author Administrator
 * 
 */
public class Http {
	private Context context;
	private static String PROXY_IP = "http://10.0.0.172:80";
	public static boolean isCMWAP = false;
	

	/**
	 * 移动资费标记
	 */
	// private final static String WAP_FLAG = "text/vnd.wap.wml";
	/**
	 * 图片上传
	 * 
	 * @param out
	 * @param imgPath
	 */
	public static void imageContentToUpload(OutputStream out, Bitmap imgpath)
			throws WeiboException {
		StringBuilder temp = new StringBuilder();

		temp.append(HttpWeibo.MP_BOUNDARY).append("\r\n");
		temp.append("Content-Disposition: form-data; name=\"pic\"; filename=\"")
				.append("memberTemp.png").append("\"\r\n");
		String filetype = "image/png";
		temp.append("Content-Type: ").append(filetype).append("\r\n\r\n");
		byte[] res = temp.toString().getBytes();
		BufferedInputStream bis = null;
		try {
			out.write(res);
			imgpath.compress(CompressFormat.PNG, 100, out);
			out.write("\r\n".getBytes());
			out.write(("\r\n" + HttpWeibo.END_MP_BOUNDARY).getBytes());
		} catch (IOException e) {
			throw new WeiboException(e);
		} finally {
			if (null != bis) {
				try {
					bis.close();
				} catch (IOException e) {
					throw new WeiboException(e);
				}
			}
		}
	}

	/**
	 * POST方法
	 * 
	 * @param urlString
	 *            接口URL
	 * @param data
	 *            请求数据
	 * @param charset
	 *            编码
	 * @param timeout
	 *            超时时间
	 * @return
	 * @throws IOException
	 */
	public static byte[] getWebContentByPost(String urlString, byte[] data,
			final String charset, int timeout) throws IOException {
		if (urlString == null || urlString.length() == 0) {
			return null;
		}
		// String rspDataString = "";
		urlString = (urlString.startsWith("http://") || urlString
				.startsWith("https://")) ? urlString : ("http://" + urlString)
				.intern();
		URL url = null;
		URLParse urlparam = new URLParse(urlString);
		
		/* 如果是wap就需要为手机添加中国移动代理，关于为手机添加中国移动的代理 */
		if(isCMWAP) {
			url = new URL(PROXY_IP + urlparam.getPath());
		} else {
			url = new URL(urlString);
		}
		HttpURLConnection connection = (HttpURLConnection) url.openConnection();
		if (isCMWAP) {
			connection.setRequestProperty("X-Online-Host", urlparam.getHost()
					+ ":" + urlparam.getPort());
		}

		// 设置是否向connection输出，因为这个是post请求，参数要放在 http正文内，因此�?��设为true
		connection.setDoOutput(true);
		connection.setDoInput(true);
		connection.setRequestMethod("POST");

		// Post 请求不能使用缓存
		connection.setUseCaches(false);
		connection.setInstanceFollowRedirects(true);
		// connection.setRequestProperty("Content-Type","application/x-www-form-urlencoded");

		/* 设置HttpURLConnection请求头里面的属性 */
		connection.setRequestProperty("Content-Type", "multipart/form-data"
				+ "; boundary=" + HttpWeibo.BOUNDARY);

		// 增加报头，模拟浏览器，防止屏蔽
		connection.setRequestProperty("User-Agent",
				"Mozilla/4.0 (compatible; MSIE 8.0; Windows xp)");

		// 只接受text/html类型，当然也可以接受图片,pdf, */*任意
		connection.setRequestProperty("Accept", "text/xml");// text/html
		connection.setConnectTimeout(timeout);
		connection.connect();
		DataOutputStream out = new DataOutputStream(
				connection.getOutputStream());
		out.write(data);

		// byte[] content = data.getBytes("UTF-8");// +URLEncoder.encode("中文")
		// out.write(content);

		out.flush();
		out.close();
		try {
			// 必须写在发�?数据的后�?
			if (connection.getResponseCode() != HttpURLConnection.HTTP_OK) {
				return null;
			}
		} catch (IOException e) {
			e.printStackTrace();
			return null;
		}
		ByteArrayOutputStream bos = new ByteArrayOutputStream(500000);
		InputStream input = connection.getInputStream();
		int ch = 0;
		while ((ch = input.read()) != -1) {
			bos.write(ch);
		}

		byte[] rspData = bos.toByteArray();
		// rspDataString = StringUtils.encodeBase64(rspData);
		return rspData;
	}

	/**
	 * POST方法
	 * 
	 * @param urlString
	 *            接口URL
	 * @param data
	 *            请求数据
	 * @return
	 * @throws IOException
	 */
	public static byte[] getWebContentByPost(String urlString, byte[] data)
			throws IOException {
		return getWebContentByPost(urlString, data, "UTF-8", 30000);
	}

	/**
	 * GET方法
	 * 
	 * @param urlString
	 *            接口URL
	 * @param charset
	 *            编码
	 * @param timeout
	 *            超时
	 * @return
	 * @throws IOException
	 */
	public static byte[] getWebContentByGet(String urlString,
			final String charset, int timeout) throws IOException {
		if (urlString == null || urlString.length() == 0) {
			return null;
		}
		// String rspDataString = "";
		urlString = (urlString.startsWith("http://") || urlString
				.startsWith("https://")) ? urlString : ("http://" + urlString)
				.intern();
		URL url = null;
		URLParse urlparam = new URLParse(urlString);
		if (isCMWAP) {
			url = new URL(PROXY_IP + urlparam.getPath());
		} else {
			url = new URL(urlString);
		}
		HttpURLConnection conn = (HttpURLConnection) url.openConnection();
		if (isCMWAP) {
			conn.setRequestProperty("X-Online-Host", urlparam.getHost() + ":"
					+ urlparam.getPort());
		}
		conn.setRequestMethod("GET");
		// 增加报头，模拟浏览器
		conn.setRequestProperty(
				"User-Agent",
				"Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.2; Trident/4.0; .NET CLR 1.1.4322; .NET CLR 2.0.50727)");
		// 只接受text/html类型，当然也可以接受图片,*/*pdf,任意，就是tomcat/conf/web里面定义那些
		conn.setRequestProperty("Accept", "text/html");
		conn.setConnectTimeout(timeout);
		// try {
		// if (conn.getResponseCode() != HttpURLConnection.HTTP_OK) {
		// return null;
		// }
		// } catch (IOException e) {
		// e.printStackTrace();
		// return null;
		// }
		ByteArrayOutputStream bos = new ByteArrayOutputStream();
		BufferedInputStream input = new BufferedInputStream(
				conn.getInputStream());
		int ch = 0;
		while ((ch = input.read()) != -1) {
			bos.write(ch);
		}

		byte[] rspData = bos.toByteArray();
		return rspData;

	}

	/**
	 * GET方法
	 * 
	 * @param urlString
	 *            接口URL
	 * @return
	 * @throws IOException
	 */
	public static byte[] getWebContentByGet(String urlString)
			throws IOException {
		return getWebContentByGet(urlString, "UTF-8", 30000);
	}

	/**
	 * 下载图片
	 * 
	 * @param urlString
	 *            接口URL
	 * @return   InputStream
	 * @throws IOException
	 */
	public static InputStream getImageString(String urlString, int timeout)
			throws IOException {
		InputStream i = null;
		urlString = (urlString.startsWith("http://") || urlString
				.startsWith("https://")) ? urlString : ("http://" + urlString)
				.intern();
		URL url = null;
		URLParse urlparam = new URLParse(urlString);

		// 如果这里不是CMWAP，不必要做那么多设置
		// if (!isCMWAP) {
		// url = new URL(urlString);
		// HttpURLConnection conn = (HttpURLConnection) url.openConnection();
		// conn.setDoInput(true);
		// conn.setConnectTimeout(timeout);
		// conn.setRequestMethod("GET");
		// conn.connect();
		// if (conn.getResponseCode() == HttpURLConnection.HTTP_OK)
		// i = conn.getInputStream();
		// return i;
		// }

		// TODO 这里需要优化
		// http://mbsns.zhangshang.mobi/upload/avatar/91467_s_1303463517.png
		// 下载不了
		if (isCMWAP) {
			url = new URL(PROXY_IP + urlparam.getPath());
		} else {
			url = new URL(urlString);
		}
		HttpURLConnection conn = (HttpURLConnection) url.openConnection();
		if (isCMWAP) {
			conn.setRequestProperty("X-Online-Host", urlparam.getHost() + ":"
					+ urlparam.getPort());
		}
		conn.setRequestMethod("GET");
		// 增加报头，模拟浏览器，防止屏蔽
		conn.setRequestProperty(
				"User-Agent",
				"Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.2; Trident/4.0; .NET CLR 1.1.4322; .NET CLR 2.0.50727)");
		// 只接受text/html类型，当然也可以接受图片,*/*pdf,任意，就是tomcat/conf/web里面定义那些
		conn.setRequestProperty("Accept", "text/html");
		conn.setConnectTimeout(timeout);
		try {
			if (conn.getResponseCode() != HttpURLConnection.HTTP_OK) {
				return null;
			}
			i = conn.getInputStream();
		} catch (IOException e) {
			e.printStackTrace();
			return null;
		}

		return i;
	}


}
